package com.stefanini.worldcupinformation.ejbs;

import com.stefanini.worldcupinformationpersistence.entities.Grupo;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@LocalBean
@Stateless
public class GroupDao {
    
    @PersistenceContext
    private EntityManager em;
    
    public void newGroup(Grupo group){
        try {
            em.persist(group);
            em.flush();
        } catch (Exception e) {
            Logger.getLogger(GroupDao.class.getName()).log(Level.SEVERE, 
                    "Error! Insertar el grupo", e);
        }
    }
    
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void edit(Grupo group){
        try {
            em.persist(group);
            em.flush();
        } catch (Exception e) {
            Logger.getLogger(GroupDao.class.getName()).log(Level.SEVERE, 
                    "Error! Editar Grupo", e);
        }
    }
    
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void delte(Grupo group){
        try {
            em.remove(group);
            em.flush();
        } catch (Exception e) {
            Logger.getLogger(GroupDao.class.getName()).log(Level.SEVERE, 
                    "Error! Eliminar Grupo", e);
        }
    }
    
    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public List<Grupo> getAll(){
        StringBuilder query = new StringBuilder();
        query.append("SELECT g FROM Grupo g");
        
        Query q = em.createQuery(query.toString(), Grupo.class);
        return q.getResultList();
    }
}
